// 游戏场景
declare function getItems(url,token);
class GameStage extends egret.Sprite{
    private gameBg:egret.Sprite;
    //private ignore:string;

    public constructor(){
        super();
         StageData.GameRoot = this;
        this.gameBg = new egret.Sprite();
        this.addChild(this.gameBg);
        this.openRomm();
        if(GameData.roundNo){
            //回放
            getItems(StageData.linkStr+"/recordCenter/roundvideo/"+GameData.roundNo,GameData.token);
            StageData.MainObj.once("playback_ok",(e)=>{
                Message.toPlayback(e.data);
                this.openVideoPlay();
            },this);
            StageData.MainObj.once("playback_error",()=>{
                this.ifClew("回放数据错误，返回到大厅！",()=>{
                    this.toLink(StageData.updateLink);
                });
            },this);
            
            // Message.toPlayback(ReplayTest.roundData);
            // this.openVideoPlay();

            return;
        }        
        if(GameData.roomConf){
            //创建房间
            this.CreationRoom();
        }else{
            //加入房间
            if(GameData.token&&GameData.roomNo){
                this.addGameRoom();
            }else{
                this.ifClew("登录遇到错误，返回到大厅！",()=>{
                     this.toLink(StageData.updateLink);
                });
            }
        }

        this.testTx.width = 200;
        this.testTx.height = 200;
        this.testTx.size = 20;
        this.addChild(this.testTx);
    }

    //打开回放控制
    private videplayObj:videoPlay;
    private openVideoPlay(){
        this.videplayObj = new videoPlay();
        this.addChild(this.videplayObj);
        this.videplayObj.addEventListener("start",()=>{
            Message.playStop = false;
            Message.toplaybackMessage();
            //alert("start");
        },this);
        this.videplayObj.addEventListener("stop",()=>{
            Message.playStop = true;
            //alert("stop");
        },this);
        this.videplayObj.addEventListener("speed",()=>{
            Message.setPlayTimer();
            //alert("speed");
        },this);
        this.videplayObj.addEventListener("replay",()=>{
            if(GameData.backurl){
                this.toLink(GameData.backurl);
            }else{
                this.toLink(StageData.updateLink);
            }
        },this);
    }
    //执行创建房间
    private CreationRoom(){
        let _confId:any=null;//玩家群玩法
        let _qiXiaoDuiWin:any = false;//七小对可胡
        let _sameIpJoin:any = false;//同IP不能进
        if(GameData.roomConf.confId){
            _confId = GameData.roomConf.confId;
        }
        if(GameData.roomConf.qiXiaoDuiWin){
            _qiXiaoDuiWin = GameData.roomConf.qiXiaoDuiWin;
        }
        if(GameData.roomConf.sameIpJoin){
            _sameIpJoin = GameData.roomConf.sameIpJoin;
        }
        //alert(_qiXiaoDuiWin+":"+_sameIpJoin);
        /*"{"roomConf":{"ruleType":5,"turns":1,"payType":1,"maxPlayerCount":4,"qiXiaoDuiWin":false,"sameIpJoin":false},"gameId":3}"*/
        // this.newGameRoom(GameData.roomConf.ruleType,GameData.roomConf.payType,GameData.roomConf.turns,_confId,_qiXiaoDuiWin,_sameIpJoin);
        this.newGameRoom(GameData.roomConf)
        
    }
    private testTx:egret.TextField = new egret.TextField();
    public clew(str:string){
        /*this.testTx.appendText("\n"+str);
        this.testTx.height = this.testTx.textHeight+5;
        this.testTx.y = (-this.testTx.height + 220);*/
    }
   
    //JSSDK 执行分享签名
    public shareInitGame(){
        //console.log("share:"+StageData.updateLink);
        //let shareUrl:string =StageData.linkStr+"/login/weiXin/"+GameData.areaCode+"?roomNo="+GameData.roomNo+"&type=10003";
       // StageData.FXOBJ.setTitle("帅帅红中麻将","好友麻将，“一码全中”“两个码”“四个码”“六个码”“八个码”，人数三人、四人多种玩法，点击进入决战到天亮....",shareUrl,"icon1");
    }

    //提示信息
    private clewobj:clewInfo;
    public ifClew(str:string,yesFun:Function=null,noFun:Function=null){        
        this.closeIfClew();
        this.clewobj = new clewInfo();
        this.addChild(this.clewobj);
        this.clewobj.clew(str,yesFun,noFun);
        this.clewobj.addEventListener(this.clewobj.OUTPUT_RESULT,this.closeIfClew,this);
    }
    private closeIfClew(){
        if(this.clewobj){
            this.clewobj.removeEventListener(this.clewobj.OUTPUT_RESULT,this.closeIfClew,this);
            this.removeChild(this.clewobj);
            this.clewobj = null;
        }
    }

    //添加游戏场景
    private mainRomm:room;
    public openRomm(){
        this.closeRoom();
        this.mainRomm = new room();
        this.gameBg.addChild(this.mainRomm);
        StageData.MainObj.addEventListener(Events.MESSAGE_RECEIVE,this.message,this);
        StageData.GameRoot.addEventListener(GameEvent.START_GAME,this.readyGame,this);
        StageData.GameRoot.addEventListener(GameEvent.CLEW_SHARE,this.openShareInfo,this);
    }
    private closeRoom(){
        if(this.mainRomm){
            this.gameBg.removeChild(this.mainRomm);
            this.mainRomm = null;
            StageData.MainObj.removeEventListener(Events.MESSAGE_RECEIVE,this.message,this);
            StageData.GameRoot.removeEventListener(GameEvent.START_GAME,this.readyGame,this);
            StageData.GameRoot.removeEventListener(GameEvent.CLEW_SHARE,this.openShareInfo,this);
        }
    }
    //打开分享提示信息
    private shareclewinfo:shareClewInfo;
    private openShareInfo(){
         this.closeShareInfo();
         this.shareclewinfo = new shareClewInfo();
         this.shareclewinfo.addEventListener(this.shareclewinfo.ON_CLOSE,this.closeShareInfo,this);
         this.addChild(this.shareclewinfo);
    }
    private closeShareInfo(){
        if(this.shareclewinfo){
            this.shareclewinfo.removeEventListener(this.shareclewinfo.ON_CLOSE,this.closeShareInfo,this);
            this.removeChild(this.shareclewinfo);
            this.shareclewinfo = null;
        }
    }
    //加入房间
    private addroom:addRoom;
    private openAddRoom(){
        this.closeAddRoom();
        this.addroom = new addRoom();
        this.addChild(this.addroom);
        this.addroom.x = (StageData.W - this.addroom.width)/2;
        this.addroom.y = (StageData.H - this.addroom.height)/2;
        this.addroom.addEventListener(this.addroom.ON_CLICK,this.addRoomReturn,this);
    }
    private addRoomReturn(e){
        if(e.data){
            GameData.roomNo = e.data;
            this.addGameRoom();
            //游戏服务器连接失败就重连
            /*StageData.MainObj.once("connectClose",()=>{
                 StageData.GameRoot.clew("游戏服务器重连...");
                 this.addGameRoom();
            },this);*/
        }else{
            // this.newGameRoom(1,1,1,null,null,null);
            // _ruleType:number,_payType:number,_turns:number,_confId,_qiXiaoDuiWin,_sameIpJoin
            this.newGameRoom({ruleType: 1, payType: 1, turns: 1})
        
            //游戏服务器连接失败就重连
            /*StageData.MainObj.once("connectClose",()=>{
                StageData.GameRoot.clew("游戏服务器重连...");
                this.newGameRoom(1,1,1,null);
            },this);*/
        }
    }
    private closeAddRoom(){
        if(this.addroom){
            this.addroom.removeEventListener(this.addroom.ON_CLICK,this.addRoomReturn,this);
            this.removeChild(this.addroom);
            this.addroom = null;
        }
    }

    //等待提示动画
    private waitObj:loadClew;
    private waitTimer;
    public openWait(jishi:Boolean=true){
        if(!this.waitObj){
            this.waitObj = new loadClew();
            this.waitObj.init();
        }
        this.addChild(this.waitObj);
        //this.addChild(MyLibrary.createBitmapByName("alphaBg_png"));
        //判断是否超时
        if(jishi){
            this.waitTimer = egret.setTimeout((e)=>{
                egret.clearTimeout(this.waitTimer);
                this.waitTimer = null;
                this.closeWait();
                this.ifClew("网络超时，请检查网络!");
             },this,8000);
        }
    }
    public closeWait(){
        if(this.waitObj){
            this.removeChild(this.waitObj);
            this.waitObj = null;
        }
        if(this.waitTimer){
            egret.clearTimeout(this.waitTimer);
            this.waitTimer = null;
        }
    }
    
    /*---------------@数据处理-------------------------*/
    private message(e){
        let msg:any = e.data;
       // console.log("\n\n\n\n"+JSON.stringify(msg));
        if(msg.step>GameData.step){
            GameData.step = msg.step;
        }        
        switch(msg.commandCode){
            //成功进入游戏
            case 11002:
            this.closeAddRoom();
            this.mainRomm.setMySeatindex(msg.seatIndex);
            this.mainRomm.openTimerDown(msg.roomCancelTimeMillis);
            break;     
            //玩家开启了3人模式
            case 10001:
            this.mainRomm.getMSGInfo(msg)
            break; 
            //玩家准备了游戏
            case 10000:
            this.mainRomm.userReadyGame(msg);
            break;
            //更新房间信息
            case 11000:
            this.mainRomm.updateRoomInfo(msg);
            break;
            //有玩家退出游戏或选择了投票
            case 11003:
            this.mainRomm.ExitRoomClew(msg);
			break;
            //玩家申请退出房间
			case 11004:
				if(msg.roomCancelTimeMillis){//自动退出房间倒计时
					this.mainRomm.openTimerDown(msg.roomCancelTimeMillis);
				}
                //this.clew("有人退出房间");
                this.mainRomm.agreeExitRoom(msg);
			break;
			//解散房间
			case 11005:
                 //alert("房间已被解散");
                 this.toLink(StageData.updateLink);
                 Message.stopHeart();
			break;
            //错误信息提示
			case 25:
                Message.stopHeart();
                if(msg.error.errorCode == 9){
                   //钻石余额不足
                    this.ifClew("您的钻石余额不足，去商场充值？",()=>{
                        this.toLink(StageData.updateLink+"&shopping=true");//加参数去到商场
                    });                   
                }else{
                    this.ifClew(msg.error.errorMsg,()=>{
                        this.toLink(StageData.updateLink);
                    });
                }  
			break;
            //重连消息
			case 11006:
                this.mainRomm.getReconnect(msg);
			break;
            
            //我收到手牌信息
			case 20001:
                this.mainRomm.acceptHandPoker(msg);   			
			break;
            //其他玩家收到手牌数量
			case 20002:
                this.mainRomm.acceptHandPokerNumber(msg);
			break;
            //轮到某玩家出牌（参数会收到一张牌）
			case 20003:
                this.mainRomm.isWhoOutPoker(msg);
			break;
            //某玩家出了牌
			case 20004:
                this.mainRomm.accepOutPoker(msg);
			break;
            //回合结束
            case 20005:      
                this.mainRomm.getRoundEnd(msg);
			break;
            //总结算
            case 20006:      
                //alert("游戏结束");
                Message.stopHeart();
                this.openWait();
                this.toLink(StageData.toRecordLink);
			break;

            //某玩家可能要碰、杠、胡
			case 20007:
                this.mainRomm.whoWin();
			break;
            //听牌
			case 20008:
			break;
            //提醒我可以碰、杠、胡
			case 20009:
            //alert("MSG:"+JSON.stringify(msg));
                this.mainRomm.winPoker(msg);
			break;
            //某玩家碰、杠、胡
			case 20010:  
            //alert("data:"+JSON.stringify(msg)); 
                this.mainRomm.getWinPoker(msg);		
			break;
            // 要海底牌的结果
			case 20013:  
            //alert("data:"+JSON.stringify(msg)); 
                this.mainRomm.getHaidiResult(msg);		
			break;
            // 分步摇筛子的结果
			case 20014:  
            //alert("data:"+JSON.stringify(msg)); 
                this.mainRomm.yaoshaiziResult(msg);		
			break; 
            // 起手胡返回的消息号
			case 20015:  
            //alert("data:"+JSON.stringify(msg)); 
                // this.mainRomm.qishouhuShow(msg);		
                this.mainRomm.qishouhuyaoshaiziResult(msg);	
			break;  
            // 玩家报听后返回给前端的消息号
			case 20016:  
            //alert("data:"+JSON.stringify(msg)); 
                // this.mainRomm.qishouhuShow(msg);		
                // this.mainRomm.yaoshaiziResult(msg);	
                this.mainRomm.baotingle(msg);
			break;  
            // 如果是在翻牌期间补张胡了（也就是昨天说的要把牌放到头像旁边）
			case 20018:  
                this.mainRomm.buzhanghule(msg);
			break;      
            //托管听牌
			case 11008:
                this.mainRomm.getTingPoker(msg);
			break;             
        }
    }

    //执行超链接
    public toLink(linkstr:string){
        window.location.href = linkstr;
    }

    /*--------------@交互操作-------------------------*/
    //加入游戏
    private addGameRoom(){
        let config = {
			user: "user",
			pass: "pass",
			roomNo:GameData.roomNo,
			token:GameData.token,
			step:GameData.step,
            ignore:GameData.ignore
		};
		Message.connectServer(config,()=>{
			let data = {
				commandCode:"11001",
				version:"0.1",
				step:GameData.step
			};
			Message.sendMsgToServer(data);
        },this.addGameRoom);
       // this.ignore = GameData.ignore;
    }
    //新建游戏 (中码类型，回合，玩家人数，支付类型,七小对可胡，同IP不能进)
    // _ruleType:number,_payType:number,_turns:number,_confId,_qiXiaoDuiWin,_sameIpJoin
    private newGameRoom(gameConf){
		let config = {
			user: "user",
			pass: "pass",
			token: GameData.token
		};
		Message.connectServer(config,()=>{
			let data = {
				commandCode:"11000",
				version:"0.1",
                gameConf
				// ruleType :_ruleType,
				// turns:_turns,
                // payType:_payType,
                // confId:_confId,
                // qiXiaoDuiWin:_qiXiaoDuiWin,
                // sameIpJoin:_sameIpJoin
			};	
			Message.sendMsgToServer(data);
		},this.CreationRoom);
	}
    
    //准备游戏
    private readyGame(){
            let data = {
			  commandCode: "10000",
			  version: "0.1",
			  ready:true,
              step:GameData.step
			};
			Message.sendMsgToServer(data);
    }
    //退出房间
    private ExitRoom(){
        let data = {
			commandCode: "11002",
			version: "0.1",
            step:GameData.step
		};
		Message.sendMsgToServer(data);
    } 
    //刷新房间信息
    public updateUoomInfo(){
        let data = {
			commandCode: "10003",
			version: "0.1",
            step:GameData.step
		};
		Message.sendMsgToServer(data);
    }
}